package controllers

import (
	"blog/models"
	"blog/syserror"
	"bytes"
	"errors"
	"github.com/PuerkitoBio/goquery"
	"github.com/jinzhu/gorm"
)

type NotesController struct {
	BaseController
}

func (this *NotesController) NextPrepare() {
	this.MustLogin()
	if this.User.Role != 0 {
		this.Abort500(errors.New("权限不足！"))
	}
}

///notes
//@router /new [get]
func (this *NotesController) Notes() {
	this.Data["title"] = "极简博客--文章详情"
	this.Data["key"] = this.UUID()
	this.TplName = "notes_new.html"
}

//@router /save/:key  [post]
func (this *NotesController) Save() {
	key := this.Ctx.Input.Param(":key")
	title := this.GetMustString("title", "标题不能为空")
	content := this.GetMustString("content", "内容不能为空")

	notes, err := models.QueryNoteByKey(key)

	var n models.Notes

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			n = models.Notes{
				Key:     key,
				Title:   title,
				Content: content,
				UserID:  int(this.User.ID),
				User:    this.User,
			}
		} else {
			this.Abort500(syserror.New(301, "保存失败！", err))
		}
	} else {
		notes.Title = title
		notes.Content = content
		n = notes
	}
	//摘要
	n.Summary, _ = getSummary(content)

	if err = models.SaveNotes(&n); err != nil {
		this.Abort500(syserror.New(301, "保存失败！", err))
	}

	this.JsonH(0, "保存成功！", H{})
}

func getSummary(html string) (string, error) {

	var bufbytes bytes.Buffer

	if _, err := bufbytes.Write([]byte(html)); err != nil {
		return "", err
	}
	doc, err := goquery.NewDocumentFromReader(&bufbytes)
	if err != nil {
		return "", err
	}
	htmlstr := doc.Find("body").Text()
	if len(htmlstr) > 600 {
		htmlstr = htmlstr[:600]
	}
	return htmlstr, nil
}
